<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2018/11/14
 * Time: 9:23
 */

namespace App\Console\Fix;

use App\Http\Helper\DataTransHelper;
use Illuminate\Console\Command;
use UserRecordService;
use TestingItemService;
use TestingAlgoHelper;

class FixRecord extends Command
{
    protected $signature = 'fix:record {--h=} {--id=} {--order_id=} {--tid=} {--index=} {--answer=} {--weight=}';

    protected $description = '修复用户答题记录';

    /**
     * MessageCommand constructor.
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * php artisan cron:sendSeminarMsg --uid=2018-10-15 --day=2018-10-17
     */
    public function handle() {
        $id = $this->option('id');
        $orderId = $this->option('order_id');
        $tid = $this->option('tid');
        $index = $this->option('index');
        $answer = $this->option('answer');
        $weight = $this->option('weight');
        if ($this->option('h')) {
            echo "命令参数：{--h=} {--index=} {--answer=} {--weight=}" . PHP_EOL;
            echo "参数描述： --h=1 查看命令描述" . PHP_EOL;
            echo "         --order_id= 需要修复的订单ID" . PHP_EOL;
            echo "         --id= 没有订单ID的话，使用record的id" . PHP_EOL;
            echo "         --index= 需要修复的题号" . PHP_EOL;
            echo "         --answer= 需要修复的答案" . PHP_EOL;
            echo "         --weight= 需要修复的权重" . PHP_EOL;
            exit;
        }
        $this->fixRecord($id, $orderId, $tid, $index, $answer, $weight);
    }

    /**
     * 修复用户的答题记录
     * @param $id
     * @param $orderId
     * @param $tid
     * @param $index
     * @param $answer
     * @param $weight
     */
    protected function fixRecord($id, $orderId, $tid, $index, $answer, $weight) {
        $userRecord = '';
        if ($orderId) { //同时输入用户和天数
            $userRecord = UserRecordService::getLastOneByOrderTid($orderId, $tid);
        } elseif ($id) { //只输入用户时
            $userRecord = UserRecordService::getById($id);
        }
        if (!$userRecord) {
            echo "测评记录不存在";
            exit(0);
        }
        $typeFourExpress = TestingItemService::typeFourItem($tid);
        $typeFourExpress = empty($typeFourExpress) ? null : $typeFourExpress;

        $answers = $userRecord['answers'];
        $answers = DataTransHelper::convertAnswer($answers);
        foreach ($answers as &$val) {
            if ($val['index'] == $index) {
                $val['weight'] = $weight;
                $val['answer'] = $answer;
            }
        }
        $answers = DataTransHelper::arrToStr($answers);

        //计算测评的结果
        $result = TestingAlgoHelper::calculate($tid, $answers, $typeFourExpress);

        $data['score'] = $result['totalScore'];
        $data['answers'] = $answers;
        $data['final_answers'] = $result['finalAnswerStr'];
        $data['id'] = $userRecord['id'];

        UserRecordService::update($data);

        echo "测评记录修改完成";
        exit(0);
    }
}